package com.takeshequ.feeds;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.annotation.view.ViewInject;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.takeshequ.BasicActivity;
import com.takeshequ.Constants;
import com.takeshequ.R;
import com.utils.HttpClientUtils;
import com.utils.HttpClientUtils.HttpResponseHandler;

public class FeedsDetailActivity extends BasicActivity {
	private int[] imageIds = new int[107];
	private Dialog builder;
	private String behaviorId;
	private static LayoutInflater mInflater;
	private PartAdapter adapter;
	private List<ListItems> mListItems = new ArrayList<ListItems>();
	@ViewInject(id = R.id.feeds_detail_listview)
	private ListView listView;
	@ViewInject(id = R.id.feeds_detail_back, click = "back")
	private Button back;

	@ViewInject(id = R.id.feeds_detail_send_msg)
	private EditText commentMsgText;

	@ViewInject(id = R.id.feeds_detail_send_btn, click = "sendMsg")
	private Button commentSendMsgBtn;

	@ViewInject(id = R.id.feeds_detail_expression_btn, click = "createExpressionDialog")
	private ImageView expressionBtn;
	private FeedsListItem feed;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.feeds_detail);
		behaviorId = getIntent().getStringExtra("behaviorId");

	}

	@Override
	protected void onResume() {
		super.onResume();
		mInflater = LayoutInflater.from(FeedsDetailActivity.this);
		mListItems = new ArrayList<ListItems>();
		adapter = new PartAdapter(mInflater);
		listView.setAdapter(adapter);
		getBehavior();
	}

	private void getBehavior() {
		Map<String, String> params = new HashMap<String, String>();
		params.put("behaviorId", behaviorId);
		params.put("pageNumber", "1");
		HttpClientUtils.get("behaviorInfo", params, new HttpResponseHandler() {

			@Override
			public void handler(String response) {
				try {
					System.out.println(response);
					JSONObject jsonObject = new JSONObject(response);
					feed = gson.fromJson(jsonObject.getString("behavior"),
							FeedsListItem.class);
					CommentPage commentList = gson.fromJson(
							jsonObject.getString("commentPage"),
							CommentPage.class);
					mListItems.clear();
					ContentItem contentItem = new ContentItem(feed);
					mListItems.add(contentItem);
					for (Comment comment : commentList.getResult()) {
						ContentItem2 contentItem2 = new ContentItem2(comment);
						mListItems.add(contentItem2);
					}
					adapter.notifyDataSetChanged();
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		});
	}

	class PartAdapter extends BaseAdapter {
		private LayoutInflater inflater;

		public PartAdapter(LayoutInflater inflater) {
			this.inflater = inflater;
		}

		@Override
		public int getCount() {
			return mListItems.size();
		}

		@Override
		public Object getItem(int position) {
			return mListItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public boolean isEnabled(int position) {
			return mListItems.get(position).isClickable();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (mListItems.size() > position) {
				return mListItems.get(position).getView(
						FeedsDetailActivity.this, convertView, mInflater);
			}
			return null;
		}
	}

	/**
	 * 创建一个表情选择对话框
	 */
	public void createExpressionDialog(View view) {
		builder = new Dialog(FeedsDetailActivity.this);
		GridView gridView = createGridView();
		builder.setContentView(gridView);
		builder.setTitle("默认表情");
		builder.show();
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Bitmap bitmap = null;
				bitmap = BitmapFactory.decodeResource(getResources(),
						imageIds[arg2 % imageIds.length]);
				ImageSpan imageSpan = new ImageSpan(FeedsDetailActivity.this,
						bitmap);
				String str = null;
				if (arg2 < 10) {
					str = "f00" + arg2;
				} else if (arg2 < 100) {
					str = "f0" + arg2;
				} else {
					str = "f" + arg2;
				}
				SpannableString spannableString = new SpannableString(str);
				spannableString.setSpan(imageSpan, 0, 4,
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				commentMsgText.append(spannableString);
				builder.dismiss();
			}
		});
	}

	/**
	 * 生成一个表情对话框中的gridview
	 * 
	 * @return
	 */
	private GridView createGridView() {
		final GridView view = new GridView(this);
		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
		// 生成107个表情的id，封装
		for (int i = 0; i < 107; i++) {
			try {
				if (i < 10) {
					Field field = R.drawable.class.getDeclaredField("f00" + i);
					int resourceId = Integer.parseInt(field.get(null)
							.toString());
					imageIds[i] = resourceId;
				} else if (i < 100) {
					Field field = R.drawable.class.getDeclaredField("f0" + i);
					int resourceId = Integer.parseInt(field.get(null)
							.toString());
					imageIds[i] = resourceId;
				} else {
					Field field = R.drawable.class.getDeclaredField("f" + i);
					int resourceId = Integer.parseInt(field.get(null)
							.toString());
					imageIds[i] = resourceId;
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			Map<String, Object> listItem = new HashMap<String, Object>();
			listItem.put("image", imageIds[i]);
			listItems.add(listItem);
		}

		SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems,
				R.layout.team_layout_single_expression_cell,
				new String[] { "image" }, new int[] { R.id.image });
		view.setAdapter(simpleAdapter);
		view.setNumColumns(6);
		view.setBackgroundColor(Color.rgb(214, 211, 214));
		view.setHorizontalSpacing(1);
		view.setVerticalSpacing(1);
		view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		view.setGravity(Gravity.CENTER);
		return view;
	}

	public void back(View v) {
		overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
		this.finish();
		// startActivity(new Intent(FeedsDetailActivity.this,
		// MainFragmentActivity.class));
	}

	public void sendMsg(View v) {
		final String content = commentMsgText.getText().toString();
		Map<String, String> params = new HashMap<String, String>();
		if (StringUtils.isEmpty(content)) {
			Toast.makeText(this, "请输入发言内容..", 2000).show();
		} else {
			params.put("memberId", Constants.memberId);
			params.put("nickName", Constants.member.getNickName());
			params.put("headImage", Constants.member.getHeadImage());
			params.put("behaviorId", behaviorId);
			params.put("cont", content);
			params.put("commentType", "1");
			HttpClientUtils.post("/praiseBehavior", params,
					new HttpResponseHandler() {

						@Override
						public void handler(String response) {
							JSONObject jsonObject;
							try {
								jsonObject = new JSONObject(response);
								feed.setCommentCount(jsonObject
										.getString("totalCount"));
								Toast.makeText(FeedsDetailActivity.this,
										"发布成功", 2000).show();
								Comment comment = new Comment();
								comment.setCont(content);
								comment.setHeadImage(Constants.member
										.getHeadImage());
								comment.setNickName(Constants.member
										.getNickName());
								SimpleDateFormat sdf = new SimpleDateFormat(
										"HH:mm");
								comment.setCommentDateString(sdf
										.format(new Date()));
								ContentItem2 contentItem2 = new ContentItem2(
										comment);
								commentMsgText.setText("");
								commentMsgText.clearFocus();
								InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
								imm.toggleSoftInput(0,
										InputMethodManager.HIDE_NOT_ALWAYS);
								mListItems.add(contentItem2);
								adapter.notifyDataSetChanged();
								listView.setSelection(mListItems.size() - 1);
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					});
		}
	}
}
